package com.hfy.shop.service.impl;

import com.hfy.model.dto.pay.PayOrderDto;
import com.hfy.model.po.good.CommonGoodPo;
import com.hfy.model.po.order.OrderPo;
import com.hfy.shop.mapper.GoodMapper;
import com.hfy.shop.mapper.OrderMapper;
import com.hfy.shop.mapper.PayMapper;
import com.hfy.shop.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import result.Result;

import java.time.LocalDateTime;

import static constants.StatusConstants.*;

/**
 * @ author 韩
 * time: 2024/9/11 17:02
 */

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private PayMapper payMapper;

    @Override
    @Transactional
    public Result payOrder(PayOrderDto dto) {
        Integer orderId = dto.getOrderId();
        OrderPo orderInfo = orderMapper.getOrderInfo(orderId);

        Integer goodId = orderInfo.getGoodId();

        LocalDateTime now = LocalDateTime.now();
        CommonGoodPo good = goodMapper.queryGoodById(goodId);
        // 1 先需要校验参数
        // 1.1 看过没过期，如果现在的时间在截止时间之后，则证明过期了
        if (now.isAfter(orderInfo.getEndTime())) {
//            // 本来过期的话，应该由定时任务去处理，这里做附加拦截处理。
//            orderMapper.finishOrder(orderId, now, ORDER_STATUS_EXCEPTION);
//            // 然后把库存恢复
//            goodMapper.unLockStore(goodId);

            return Result.error("该订单已经过期，请重新下单！");
        }
        // 1.2 看一下状态是不是待支付状态
        if (orderInfo.getStatus() != 0) return Result.error("该订单已被处理，请刷新重试");
        // 1.3 看余额够不够
        Boolean isEnough = payMapper.checkBalance(orderInfo.getAccount(), good.getSalePrice());
        // 2.1 如果不够，直接报错余额不足
        if (!isEnough) return Result.error("你的余额不足，无法完成支付");
        // 2.2 如果够，扣减余额
        payMapper.decreaseBalance(orderInfo.getAccount(), good.getSalePrice());
        // 2 需要进行三个方面的处理
        // 2.1 商品给增加销量等等
        goodMapper.increaseSales(goodId);
        // 2.2 设置订单状态，截至时间等
        orderMapper.finishOrder(orderId, now, ORDER_STATUS_SUCCESS);
        // 2.3 记录支付日志
        payMapper.logPay(good.getSalePrice(), good.getPayType(), orderInfo.getAccount(), now, goodId);
//        return null;
        return Result.ok("支付成功");

    }
}
